package listeners;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestLEvalVisitor {
    // visitor calculator
    public static class EvalVisitor extends LExprBaseVisitor<Integer> {
        public Integer visitMult(LExprParser.MultContext context) {
            return visit(context.e(0)) * visit(context.e(1));
        }

        public Integer visitAdd(LExprParser.AddContext context) {
            return visit(context.e(0)) + visit(context.e(1));
        }

        public Integer visitInt(LExprParser.IntContext context) {
            return Integer.parseInt(context.INT().getText());
        }
    }

    public static void main(String[] args) throws IOException {
        String inputFile = null;
        if (args.length > 0) {
            inputFile = args[0];
        }
        InputStream is = System.in;
        if(inputFile != null) {
            is = new FileInputStream(inputFile);
        }

        CharStream input = CharStreams.fromStream(is);
        LExprLexer lexer = new LExprLexer(input);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        LExprParser parser = new LExprParser(tokenStream);
        ParseTree tree = parser.s();

        System.out.println(tree.toStringTree(parser));
        EvalVisitor visitor = new EvalVisitor();
        int result = visitor.visit(tree);
        System.out.println("visit properties result = " + result);

    }
}
